import userStoreCreater from '@/store/userStore'
import menuStoreCreater from '@/store/menuStore'
import tabsStoreCreater from '@/store/tabsStore'
import { loginApi } from '@/api/system/user'
import { getMenuApi } from '@/api/system/menu'
import { router, addMenuRoutes } from '@/router'

export function useLogin() {
  const menuStore = menuStoreCreater()
  const userStore = userStoreCreater()

  // 登录
  const toLogin = (params) => {
    return new Promise((resolve, reject) => {
      loginApi(params)
        .then((res) => {
          userStore.$patch((state) => {
            state.token = res.result.token
            state.user = res.result.user
          })
          resolve()
        })
        .catch((e) => {
          reject(e)
        })
    })
  }
  const resetMenuId = (pid, menuArr) => {
    menuArr.forEach((m) => {
      m.id = pid + '-' + m.id
      if (m.children && m.children.length > 0) {
        resetMenuId(m.id, m.children)
      }
    })
  }

  // 获取菜单信息
  const getMenuInfo = (params) => {
    return new Promise((resolve, reject) => {
      getMenuApi(params)
        .then((res) => {
          // 重置菜单唯一标识id
          res.result.forEach((item) => {
            resetMenuId(item.id, item.menu)
          })

          menuStore.modules = res.result
          menuStore.moduleId = menuStore.getModules[0].id
          // menuStore.$patch((state) => {
          //   state.modules = res.result
          //   state.moduleId = state.getModules[0].id // 默认选中模块一
          // })
          resolve()
        })
        .catch((e) => {
          reject(e)
        })
    })
  }

  // 登录入口
  const login = async (params) => {
    await toLogin(params) //登录
    await getMenuInfo() //获取菜单数据
    addMenuRoutes(router) // 动态添加路由 这里比较麻烦😊
    router.replace('/') // 跳转路由
  }

  return {
    login,
  }
}

export function useLogout() {
  const logout = () => {
    router.removeRoute('index')
    router.replace('/login')

    const userStore = userStoreCreater()
    const menuStore = menuStoreCreater()
    const tabsStore = tabsStoreCreater()
    userStore.$reset()
    menuStore.$reset()
    tabsStore.$reset()

    // window.location.reload(); 刷新页面也可以，但加载会慢一些
    // localStorage.clear() 清除无效
    // localStorage.removeItem('user_state')
  }
  return {
    logout,
  }
}
